import { onLoad, onShow } from "@dcloudio/uni-app";
import { reactive, ref } from "vue";
import { objectAny } from "../../options/base";
import { mySchoolStore } from "../../store";
import { addressRule,  getMySelf, getUserAddressList } from "../../utils/doCloud";
import { goToBack, goToPage, showModal, showToast } from "../../utils/utils";




const defaultAddressList:Array<addressRule> = new Array(5).fill({
    address: `默认地址`,
    name: `默认地址`,
    moblie: `默认手机号码`,
    is_default: false,
    _id: ``
})

const db = uniCloud.database()

export default {
    setup() {
        const pageType=ref<`select` | `view`>('view');
        const loading = ref(true);
        const mySelf = getMySelf();
        const mySchool = mySchoolStore();
        const addressList = ref<Array<addressRule>>(defaultAddressList);

        onLoad((options) => {
            const params = options as { type: `select` | `view` };
            pageType.value=params.type
        })

        onShow(async () => {
            await getData();
            loading.value = false;
        })

        const  getData=async ()=>{
            const { data:list} = await getUserAddressList(mySchool.mySchool._id);
            if(list){
                addressList.value=list;
            }
        }
        const select=(it:objectAny)=>{
            if(pageType.value!=='select'){
                return false;
            }
            uni.setStorageSync(`selectAddress`,JSON.stringify(it));
            goToBack();            
        }

        const remove = async (it: { _id: string; }) => {

            const status = await showModal({
                title: `安全提示`,
                content: `您确定要删除该地址？`
            })
            if (status) {
                uni.showLoading({ title: `正在删除`, mask: true });

                const { _id: user_id } = await mySelf
                try {
                    const { result } = await db
                        .collection(`admin-user-address`)
                        .where({
                            _id:it._id,
                            user_id:user_id
                        })
                        .remove();
                    if (result.errCode === 0) {
                        await getData();
                        return showToast(`删除成功`);
                    }
                } catch (error) {
                    console.log(error)
                }
                showToast(`删除失败`, 'error');

            }
        }

        return {
            loading,
            addressList,
            mySchool,
            goToPage,
            remove,
            select
        }

    }
}